package com.wxt.eventbusanalysis;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.wxt.annotations.BindView;
import com.wxt.api.interfaces.MyViewBinder;
import com.wxt.eventbusanalysis.annotationTest.api.MyApi;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.fab)
    FloatingActionButton fab;

    @BindView(R.id.clicButton)
    Button clicButton;

    EventBusEngine mEngine = new EventBusEngine();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyViewBinder.bind(this);
        setSupportActionBar(toolbar);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        clicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                click(v);
            }
        });
        mEngine.register(this);
    }

    public void click(View v) {
        Log.e("WXT", "==========time start========" + System.currentTimeMillis());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = new MyApi().testApi();
                Log.e("WXT", "==============" + result);
                mEngine.post(new MyMessage(result));
            }
        }).start();

    }

    public void onEventMainThread(MyMessage object) {
        //eventbus < 3.0
        String msg = object.msg;
        Snackbar.make(clicButton, msg, Snackbar.LENGTH_LONG).show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MyMessage object) {
        //eventbus 3.0
        String msg = object.msg;
//        Snackbar.make(clicButton, msg, Snackbar.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mEngine.unRegister(this);
    }

    class MyMessage extends Object {

        String msg;

        public MyMessage(String msg) {
            this.msg = msg;
        }

    }
}
